USE [QLDL]
GO

/****** Object:  StoredProcedure [dbo].[sp_ThemPhieuXuatHang]    Script Date: 01/10/2011 11:19:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[sp_ThemPhieuXuatHang]
	@MaDaiLy nvarchar(10), @NgayLap date, @TongTien money
as
begin
	declare @NgayTiepNhan date
	declare @TienNo money
	declare @TienNoToiDa money
	select @NgayTiepNhan = NgayTiepNhan, @TienNo = TienNo, @TienNoToiDa = TienNoToiDa 
		from DAILY, LOAIDAILY where (DAILY.MaLoaiDaiLy = LOAIDAILY.MaLoaiDaiLy) and (MaDaiLy = @MaDaiLy)
	if(@NgayLap < @NgayTiepNhan)
		return 1
		
	if (@TongTien + @TienNo > @TienNoToiDa)
		return 2
		
	declare @MaPhieuXuat nvarchar(10)
	select @MaPhieuXuat = MaPhieuXuat from PHIEUXUATHANG order by (CAST(RIGHT(MaPhieuXuat, LEN(MaPhieuXuat) - 3) as int)) asc
	if (@MaPhieuXuat is not null)
		set @MaPhieuXuat = N'PXH' + CAST((CAST(RIGHT(@MaPhieuXuat, LEN(@MaPhieuXuat) - 3) as int) + 1) as nvarchar)
	else
		set @MaPhieuXuat = N'PXH1'
		
	insert into PHIEUXUATHANG values(@MaPhieuXuat, @MaDaiLy, @NgayLap, 0)
	select MaPhieuXuat from PHIEUXUATHANG where MaPhieuXuat = @MaPhieuXuat
	return 0
end
GO


